/**
 * 图片URL处理指令
 * 自动处理图片的src属性，区分本地存储和云存储
 * 
 * 使用方法：
 * <img v-img-src="imageUrl" />
 * <el-image v-img-src="imageUrl" />
 */

import type { Directive, DirectiveBinding } from 'vue'
import { getImageUrl } from '@/utils/image'

const imageSrcDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    updateImageSrc(el, binding.value)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    if (binding.value !== binding.oldValue) {
      updateImageSrc(el, binding.value)
    }
  }
}

function updateImageSrc(el: HTMLElement, url: string) {
  const processedUrl = getImageUrl(url)
  
  // 如果是 img 标签
  if (el.tagName === 'IMG') {
    ;(el as HTMLImageElement).src = processedUrl
  } 
  // 如果是 el-image 组件
  else if (el.classList.contains('el-image')) {
    const img = el.querySelector('img')
    if (img) {
      img.src = processedUrl
    }
  }
  // 如果是其他元素，设置为背景图
  else {
    el.style.backgroundImage = `url(${processedUrl})`
  }
}

export default imageSrcDirective

